﻿using System.Collections.Generic;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class RssFeedsPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IRssFeedsView _view;

        public RssFeedsPresenter(IRssFeedsView view)
            : this(view, new RepositoryFactory())
        {
        }

        public RssFeedsPresenter(IRssFeedsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.RssFeeds)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetRssFeeds();
        }

        public void SetRssFeeds()
        {
            _view.SetRssFeeds(_administrator.CurrentSite.RssFeeds);
        }

        public void DeleteRssFeed(int id)
        {
            RssFeed rssFeed = ContentRepository.GetRssFeed(id);
            foreach (Category category in rssFeed.Categories)
            {
                category.RssFeeds.Remove(rssFeed);
            }
            rssFeed.Categories.Clear();
            foreach (UserGroup group in rssFeed.RequiredUserGroups)
            {
                group.SelectedRssFeeds.Remove(rssFeed);
            }
            rssFeed.RequiredUserGroups.Clear();
            rssFeed.Site.RssFeeds.Remove(rssFeed);
            rssFeed.Site = null;
            SiteRepository.SaveSite(_administrator.CurrentSite);
            SetRssFeeds();
        }
    }
}